// var url_service = "localhost:9555";
var url_service = "124.222.147.63:9555";

var userId = getPV('userId');
var sessionId = getPV('sessionId');
var pageNo = 1;
var pageSize = 20;
var isHaveXchat = true;

$(function () {
    // 获取历史记录
    getMessage(true);
    // 回车键发送消息事件
    enterEveter();
})

function getMessage(isFisrt) {
    if (!isHaveXchat)
        return;
    var xchatHtml = '';
    $.ajax({
        type: 'GET',
        url: 'http://' + url_service + '/api/xchat/list?pageNo=' + pageNo + '&pageSize=' + pageSize + '&sessionId=' + sessionId + '&userId=' + userId,
        dataType: 'json',
        async: false,
        success: function (res) {
            if (res.success) {
                if (Array.isArray(res.data.records) && res.data.records.length){
                    for (let item of res.data.records) {
                        var itemHtml = getXchatItemHtml(item);
                        xchatHtml += itemHtml;
                    }
                    if (isFisrt){
                        $("#messageDiv").html(xchatHtml);
                        chatReturn();
                    }else{
                        var curentHeight = getRollHeight();
                        $("#messageDiv").prepend(xchatHtml);
                        roll(curentHeight);
                    }
                    pageNo++;
                }else{
                    isHaveXchat = false;
                }
            }
        }
    })
}

function updateWidth(option) {
    var current_width = 40;
    for (let item of $(option).val()) {
        if (isChinese(item))
            current_width += 15;
        else
            current_width += 8;
    }
    $(option).css("width", current_width + "px");
}

function isChinese(temp) {
    var re = /[^\u4E00-\u9FA5]/;
    if (re.test(temp)) return false;
    return true;
}

function getPV(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

function enterEveter() {
    document.onkeydown = function (e) {
        var keycode = document.all ? event.keyCode : e.which;
        if (keycode == 13) {
            send();
        }
    }
}

let websocket = null;
if ('WebSocket' in window) {
    websocket = new WebSocket("ws://" + url_service + "/webSocket/" + userId + '@' + sessionId);
} else {
    alert('浏览器不支持webSocket');
}

//连接发生错误的回调方法
websocket.onerror = function () {
    console.log("SpringBoot Websocket 链接失败!")
};

//连接成功建立的回调方法
websocket.onopen = function (event) {
    console.log("SpringBoot Websocket 链接成功!")
};

//连接关闭的回调方法
websocket.onclose = function () {
    console.log("SpringBoot Websocket 关闭链接!")
};

//关闭连接
function closeWebSocket() {
    websocket.close();
};

//发送消息
function send() {
    if (sessionId === '' || sessionId === null || sessionId === undefined) {
        layer.open({
            title: false
            , content: " 请选择聊天会话再进行发消息好嘛？亲 "
            , btn: ['好嘟']
        });
        return;
    }
    var messageValue = $("#messageValue").val();
    if (messageValue === '' || messageValue === null || messageValue === undefined)
        return;
    let xchatContet = {
        userId: userId,
        content: messageValue,
        sessionId: sessionId
    }
    websocket.send(JSON.stringify(xchatContet));
    $("#messageValue").val("");
};

//接收到消息的回调方法
websocket.onmessage = function (event) {
    let data = event.data;
    var xchatHtml = $("#messageDiv").html();
    var itemHtml = getXchatItemHtml(JSON.parse(data), '');
    xchatHtml += itemHtml;
    $("#messageDiv").html(xchatHtml);
    chatReturn();
};

function getXchatItemHtml(item) {
    var html;
    if (item.me) {
        html = "  <div class=\"xchatItem_right\">" +
            "    <div class=\"messageDivBg rightItemBg\" onclick='copyContent(this)'>"+item.content+"</div>" +
            "    <img class=\"icon rightIcon\" src=\"" + item.userCover + "\" />" +
            "  </div>";
    } else {
        html = "  <div class=\"xchatItem_left\">" +
            "    <img class=\"icon leftIcon\" src=\"" + item.userCover + "\" />" +
            "    <div class=\"messageDivBg\" onclick='copyContent(this)'>"+item.content+"</div>" +
            "  </div>";
    }
    return html;
}

function copyContent(_this) {
    let copyInput = document.createElement('input');//创建input元素
    document.body.appendChild(copyInput);//向页面底部追加输入框
    copyInput.setAttribute('value', $(_this).html());//添加属性，将url赋值给input元素的value属性
    copyInput.select();//选择input元素
    document.execCommand("Copy");//执行复制命令
    copyInput.remove();//删除动态创建的节点
}

function chatReturn() {
    var div = document.getElementById('messageDiv');
    div.scrollTop = div.scrollHeight;
}

function roll(height) {
    var md = document.getElementById('messageDiv');
    var allHeight = md.scrollHeight;
    document.getElementById('messageDiv').scrollTop = allHeight - height - 50 ;
}

function getRollHeight() {
    return document.getElementById('messageDiv').scrollHeight;
}

var isImgNone = true;

$('#messageDiv').unbind("scroll").on("scroll", function (e) {
    var $obj = $(this);
    if ($obj.scrollTop() === 0){
        $("#loadingImg").css('display','block');
        isImgNone = false;
    } else {
        if (!isImgNone){
            $("#loadingImg").css('display','none');
            isImgNone = true;
        }
    }
});